package com.zhihuichongcheng.application.ui.approval.activity;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.smartlib.cmnObject.util.DateUtil;
import com.smartlib.cmnObject.util.DialogUtil;
import com.smartlib.cmnObject.util.GsonUtil;
import com.smartlib.cmnObject.util.LogUtil;
import com.smartlib.cmnObject.util.ToastOpt;
import com.zhihuichongcheng.application.R;
import com.zhihuichongcheng.application.base.BaseActivity;
import com.zhihuichongcheng.application.bean.approval.ApprovalWaitBean;
import com.zhihuichongcheng.application.bean.approval.Tasks;
import com.zhihuichongcheng.application.bean.approval.UserFormInfo;
import com.zhihuichongcheng.application.constant.Constants;
import com.zhihuichongcheng.application.constant.NetworkAPI;
import com.zhihuichongcheng.application.net.HttpCallback;
import com.zhihuichongcheng.application.util.OpenFiles;
import com.zhihuichongcheng.application.util.StringUtils;
import com.zhihuichongcheng.application.widget.ZoomWebView;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * Created by 3water on 2016/11/10.
 */
public class ApprovalDetailActivity extends BaseActivity implements View.OnClickListener {
    public static final int REQUEST_CODE_COMMIT = 12345;
    private RelativeLayout mRlComment;
    private TextView mTvAgree, mTvRefuse, mTvTime, mTvUsername, mTvTitle, mTvCommentNum;
    private ZoomWebView mWebView;
    private LinearLayout mLlBottom;
    private String mUserFormInstanceId, mTaskId, mType, mTitle, mFlowImg;
    private ApprovalWaitBean bean;

    //附件下载
    private RelativeLayout mRlDownload;
    private TextView mTvDownloadTitle, mTvDownloadProgress;
    private ProgressBar mBar;
    private ImageView mImDownloadType;
    private long mDownloadId;
    private DownloadManager mDownloadManager;
    private String mFilePath;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };

    private ContentObserver downloadObserver = new ContentObserver(mHandler) {
        @RequiresApi(api = Build.VERSION_CODES.GINGERBREAD)
        @SuppressLint({"WrongConstant", "SetTextI18n"})
        @Override
        public void onChange(boolean selfChange) {
            super.onChange(selfChange);
            LogUtil.logD("===========");
            DownloadManager.Query query = new DownloadManager.Query().setFilterById(mDownloadId);
            Cursor cursor = null;
            try {
                cursor = mDownloadManager.query(query);
                if (cursor != null && cursor.moveToFirst()) {
                    long downloadedBytes = cursor.getLong(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
                    long totalBytes = cursor.getLong(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
                    LogUtil.logD("downloadedBytes======" + downloadedBytes + "/n  " + "totalBytes=" + totalBytes);
                    if (downloadedBytes == totalBytes) {
                        mRlDownload.setVisibility(View.GONE);
                        getContentResolver().unregisterContentObserver(downloadObserver);
                        openFile(mFilePath);
                    } else {
                        mBar.setProgress((int) ((downloadedBytes) * 100 / totalBytes));
                        mRlDownload.setVisibility(View.VISIBLE);
                    }
                    mTvDownloadProgress.setText(mBar.getProgress() + "%");
                }
            } finally {
                if (cursor != null) {
                    cursor.close();
                }
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_approval_detail);
        initView();
        initData();
    }

    private void initView() {
        setTitle("表单详情");
        mTvCommentNum = (TextView) findViewById(R.id.tv_comment_num);
        mLlBottom = (LinearLayout) findViewById(R.id.ll_bottom);
        mTvTime = (TextView) findViewById(R.id.tv_time);
        setTvRight("流程", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != bean && null != bean.getUserFormInfo() && !StringUtils.isEmpty(bean.getUserFormInfo().getFlowImg())) {
                    Bundle bundle = new Bundle();
                    bundle.putString("flowImg", bean.getUserFormInfo().getFlowImg());
                    startActivity(ApprovalProcessActivity.class, bundle);
                } else {
                    ToastOpt.createToast(getContext(), "流程图未找到");
                }
            }
        });
        mTvTitle = (TextView) findViewById(R.id.tv_title);
        mTvUsername = (TextView) findViewById(R.id.tv_name);
        mRlComment = (RelativeLayout) findViewById(R.id.rl_comment);
        mTvAgree = (TextView) findViewById(R.id.tv_agree);
        mTvRefuse = (TextView) findViewById(R.id.tv_refuse);
        mWebView = (ZoomWebView) findViewById(R.id.webview);

        //附件下载相关View
        mImDownloadType = (ImageView) findViewById(R.id.im_download_type);
        mTvDownloadTitle = (TextView) findViewById(R.id.tv_download_title);
        mTvDownloadProgress = (TextView) findViewById(R.id.tv_download_progress);
        mRlDownload = (RelativeLayout) findViewById(R.id.rl_download);
        mBar = (ProgressBar) findViewById(R.id.progress_bar);

        mRlComment.setOnClickListener(this);
        mTvAgree.setOnClickListener(this);
        mTvRefuse.setOnClickListener(this);
    }

    @SuppressLint({"WrongConstant", "AddJavascriptInterface"})
    private void initData() {
        Intent intent = getIntent();
        if (intent != null) {
            if (intent.hasExtra("userFormInstanceId")) {
                mUserFormInstanceId = intent.getStringExtra("userFormInstanceId");
            }
            if (intent.hasExtra("taskId")) {
                mTaskId = intent.getStringExtra("taskId");
            }
            if (intent.hasExtra("type")) {
                mType = intent.getStringExtra("type");
            }
        }
        if (!TextUtils.isEmpty(mType) && mType.equals("1")) {
            mLlBottom.setVisibility(View.GONE);
        }

        mWebView.disableControls();

        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress == 100) {
                    DialogUtil.dismiss(mContext);
                }
            }
        });
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });
        mWebView.addJavascriptInterface(this, "approval");
        HashMap<String, String> params = new HashMap<>();
        params.put("token", mUser.getToken());
        params.put("userFormInstanceId", mUserFormInstanceId);
        if (!TextUtils.isEmpty(mTaskId)) {
            params.put("taskId", mTaskId);
        } else {
            params.put("taskId", " ");
        }
        DialogUtil.showLoadDiadlog(mContext);
        mManager.post(NetworkAPI.Approval_Audio_View, new HttpCallback() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onSuccess(int code, String value, String msg) {
                if (!StringUtils.isEmpty(value)) {
                    bean = GsonUtil.praseFromStringToBean(value, ApprovalWaitBean.class);
                    mTvTitle.setText(bean.getTitle());
                    mTvUsername.setText(bean.getUser().getUserName());
                    Date date = DateUtil.parseStringToDate(bean.getCreateTime(), "yyyy年MM月dd日 HH:mm:ss");
                    mTvTime.setText(DateUtil.formatDateToString(date, "MM-dd HH:mm"));
                    UserFormInfo info = bean.getUserFormInfo();
                    List<Tasks> tasksList = bean.getTasks();
                    if (tasksList != null) {
                        mTvCommentNum.setText(tasksList.size() + "");
                    } else {
                        mTvCommentNum.setText("0");
                    }
                } else {
                    mTvCommentNum.setText("--");
                }
                String linkUrl = NetworkAPI.Approval_detail_web + "?taskId=" + mTaskId
                        + "&userFormInstanceId=" + mUserFormInstanceId
                        + "&token=" + mUser.getToken();
                LogUtil.logD("--linkUrl-->" + linkUrl);
                mWebView.loadUrl(linkUrl);
            }

            @Override
            public void onFailure(String value) {
                DialogUtil.dismiss(mContext);
            }
        }, params);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_comment:
                if (null != bean && null != bean.getTasks()) {
                    Bundle bundle = new Bundle();
                    bundle.putParcelableArrayList("comment", (ArrayList) bean.getTasks());
                    startActivity(ApprovalCommentActivity.class, bundle);
                }
                break;
            case R.id.tv_agree:
                if (null != bean && null != bean.getTaskId()) {
                    Bundle bundle = new Bundle();

                    bundle.putString("userFormInstanceId", bean.getUserFormInstanceId());
                    bundle.putString("taskId", bean.getTaskId());
                    UserFormInfo info = bean.getUserFormInfo();
                    if (info != null) {
                        bundle.putString("remark", info.getRemark());
                    }

                    startActivityForResult(ApprovalSubmitActivity.class, REQUEST_CODE_COMMIT, bundle);
                }
                break;
            case R.id.tv_refuse:
                if (null != bean && null != bean.getTaskId()) {
                    Bundle bundleRef = new Bundle();
                    bundleRef.putString("userFormInstanceId", bean.getUserFormInstanceId());
                    bundleRef.putString("taskId", bean.getTaskId());
                    UserFormInfo info = bean.getUserFormInfo();
                    if (info != null) {
                        bundleRef.putString("remark", info.getRemark());
                    }
                    startActivityForResult(ApprovalRefuseActivity.class, REQUEST_CODE_COMMIT, bundleRef);
                }
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_COMMIT && resultCode == RESULT_OK) {
            setResult(RESULT_OK);
            finish();
        }
    }

    @android.webkit.JavascriptInterface
    public void bridgeDownload(final String url) {
        runOnUiThread(new Runnable() {
            @TargetApi(Build.VERSION_CODES.HONEYCOMB)
            @RequiresApi(api = Build.VERSION_CODES.GINGERBREAD)
            @SuppressLint("WrongConstant")
            @Override
            public void run() {
                String[] strs = url.split("/");
                LogUtil.logD(strs[strs.length - 1]);
                mFilePath = Constants.Const_Cache_Dir + "/" + strs[strs.length - 1];
                File file = new File(mFilePath);
                if (file.exists()) {
                    openFile(mFilePath);
                    return;
                }
                mDownloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
                Uri uri = Uri.parse(url);
                DownloadManager.Request request = new DownloadManager.Request(uri);
                request.setNotificationVisibility(View.VISIBLE);
                request.setDestinationInExternalPublicDir("/ThreeWaterbeijing/download/", strs[strs.length - 1]);
                mDownloadId = mDownloadManager.enqueue(request);
                getContentResolver().registerContentObserver(Uri.parse("content://downloads/my_downloads"), true, downloadObserver);
            }
        });

    }

    private void openFile(String path) {
        if (null == path) return;
        OpenFiles.openFile(this, path);
    }

    @android.webkit.JavascriptInterface
    public void appFormSubmitSuccess() {
        runOnUiThread(new Runnable() {
            @TargetApi(Build.VERSION_CODES.HONEYCOMB)
            @RequiresApi(api = Build.VERSION_CODES.GINGERBREAD)
            @SuppressLint("WrongConstant")
            @Override
            public void run() {
                Bundle bundle = new Bundle();
                bundle.putInt("type", 1);
                bundle.putString("title", "我已审批");
                startActivity(ApprovalListActivity.class, bundle);
                finish();
            }
        });

    }
}

